package cn.fl.ref.contract.controller;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.comm.facade.upload.dto.SysUlFilesRecDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.ref.contract.service.IFncPrjContDetailService;
import cn.fl.ref.contract.service.IFncPrjContMainApplyService;
import cn.fl.ref.contract.service.IFncPrjContMainService;
import cn.fl.ref.contract.vo.FncPrjContDetailVO;
import cn.fl.ref.contract.vo.FncPrjContMainApplyVO;
import cn.fl.ref.fncprjbscinfo.service.IFncPrjBscInfoService;
import cn.fl.ref.fribaseinfo.transform.FriBaseFlowVOTransform;
import cn.fl.ref.fribaseinfo.vo.FriBaseFlowVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.vo.SysUlFilesRecVO;
import fl.ref.contract.constant.FncPrjContMainConstant;
import fl.ref.fncprjbscinfo.constant.FncPrjBaseInfoConstant;
import fl.ref.fribaseinfo.condition.FriBaseInfoQueryCondition;
import fl.ref.fribaseinfo.dto.FriBaseFlowDTO;

/**
 * @Description:  再融资合同审核 控制层
 */
@Controller
@RequestMapping("/rfcont/fncPrjContAudit")
public class FncPrjContAuditController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(FncPrjContAuditController.class);

	@Autowired
	private IFncPrjContMainService fncPrjContMainService;//合同服务
	@Autowired
	private IFncPrjContDetailService fncPrjContDetailService;//合同明细表服务
	@Autowired
	private IFncPrjContMainApplyService fncPrjContMainApplyService;//合同申请主表服务
	@Autowired
	IFncPrjBscInfoService fncPrjBscInfoService;//项目服务
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;//字典服务
	@Autowired
	private ISysUlFilesRecService sysUlFilesRecService;//附件服务
	@Autowired
    private IUploadApiService uploadApiService;
	
	/**
	 * 再融资合同审核流程附加页面
	 */
	@RequestMapping("/audit.do")
	public String audit(HttpServletRequest request,HttpServletResponse response) {
		String contId = request.getParameter("contId");//合同主表id
		String from = request.getParameter("from");
		
		if(StringUtils.isNotBlank(contId)) {
			//查询合同信息，关联项目、授信等信息
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("contId", contId);
			Map<String, Object> prjScmCr = fncPrjContMainService.selectPrjScmCr(param);
					
			if("refManager".equals(from)) {//如果修改页面，则需跳转 
				return	"redirect:/rfbuss/fncPrjContMain/toAddContPage.do?prjId="+prjScmCr.get("ID")+"&from="+from;
			}
			
			this.setDicInfo(prjScmCr);
					
			request.setAttribute("prjScmCr", prjScmCr);
			request.setAttribute("from", from);
		}
		BaseLogUtils.info(logger, "audit", "再融资合同审核流程附加页面.[from="+from+"] contId:" + contId, CurrentThreadContext.getCurrentUserName());
		return "rfbuss/fncPrjContMain/fncPrjContAudit";
	}
	/**
	 * 再融资合同审核流程附加页面新(流程业务主键来源于合同申请主表)
	 */
	@RequestMapping("/auditn.do")
	public String auditn(HttpServletRequest request,HttpServletResponse response) {
		String applyId = request.getParameter("contId");//合同申请主表id
		String from = request.getParameter("from");
		
		if(StringUtils.isNotBlank(applyId)) {
			//根据合同申请主表Id获取信息
			FncPrjContMainApplyVO applyVo=fncPrjContMainApplyService.selectById(Long.parseLong(applyId));
			if(applyVo.getFncPrjContMainId()!=null){
				if(StringUtils.isNotEmpty(applyVo.getFncPrjContMainId())){
					//查询合同信息，关联项目、授信等信息
					Map<String, Object> param = new HashMap<String, Object>();
					param.put("contId", applyVo.getFncPrjContMainId());
					Map<String, Object> prjScmCr = fncPrjContMainService.selectPrjScmCr(param);
					if("refManager".equals(from)) {//如果修改页面，则需跳转 
						return	"redirect:/rfbuss/fncPrjContMain/toModifyFncPrjCont.do?prjId="+prjScmCr.get("ID")+"&from="+from+"&applyId="+applyId;
					}
					this.setDicInfo(prjScmCr);
					request.setAttribute("prjScmCr", prjScmCr);
				}
			}
			request.setAttribute("from", from);
		}
		request.setAttribute("applyId", applyId);
		BaseLogUtils.info(logger, "audit", "再融资合同审核流程附加页面.[from="+from+"] applyId:" + applyId, CurrentThreadContext.getCurrentUserName());
		return "rfbuss/fncPrjContMain/fncPrjContAuditFlow";
	}
	/**
	 * 设置字典项信息
	 * @param VO
	 */
	private void setDicInfo(Map<String, Object> prjScmCr) {
		String sysCd = CurrentThreadContext.getCurrentSysCd();
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		
		Map<String, String> bustypelist = this.sysDictionaryApiService
				.searchGroupToMap(sysCd, orgCd,
						FncPrjBaseInfoConstant.FNC_PRJ_BSC_INFO_BUS_TYPE);
		
		// 业务类型
		if (bustypelist.containsKey(prjScmCr.get("BUS_TYPE"))) {
			prjScmCr.put("BUS_TYPE_",bustypelist.get(prjScmCr.get("BUS_TYPE")));
		}
		
		// 首付款计算
		BigDecimal FSTPY_AMT = (BigDecimal)prjScmCr.get("FSTPY_AMT");
		if(FSTPY_AMT == null) {
			FSTPY_AMT = new BigDecimal(0);
		}
		
		
		BigDecimal FSTPY_DEP_ADD;
		try {
			FSTPY_DEP_ADD = new BigDecimal((String)prjScmCr.get("FSTPY_DEP_ADD"));
		} catch (Exception e) {
			e.printStackTrace();
			BaseLogUtils.info(logger, "setDicInfo", "再融资合同审核流程附加页面：FSTPY_DEP_ADD无法转成BigDecimal " + e.getMessage(), CurrentThreadContext.getCurrentUserName());
			FSTPY_DEP_ADD = new BigDecimal(0);
		}
		
		prjScmCr.put("firstPayment",FSTPY_AMT.add(FSTPY_DEP_ADD));
		
	}
	
	/**
	 * 合同明细列表数据
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/contDetailList.do")
	@ResponseBody
	public Object contDetailList(HttpServletRequest request) {
		String contId = request.getParameter("contId");
		if(StringUtils.isNotBlank(contId)) {
			List<Map<String, Object>> prjContDetailList = fncPrjContMainService.selectPrjContDetailList(Long.valueOf(contId));
			for (Map<String, Object> prjContDetail : prjContDetailList) {
				this.setPrjContDetailAttche(prjContDetail);//设置合同附件
				this.contDetailRiskAttachList(prjContDetail);//设置风控审核附件
				this.setPrjContDetailFinal(prjContDetail);//设置最终版
				prjContDetail.put("prjContOptionList", fncPrjContMainService.selectPrjContOptionList(((BigDecimal) prjContDetail.get("ID")).longValue()));//风控意见
			}
			
			ListPageVO listPageVO = new ListPageVO(prjContDetailList, prjContDetailList.size());
			return listPageVO;
		}
		BaseLogUtils.info(logger, "contDetailList", "合同明细列表数据 contId:" + contId, CurrentThreadContext.getCurrentUserName());
		return null;
	}
	
	//设置合同附件
	private void setPrjContDetailAttche(Map<String, Object> prjContDetail) {

		SysUlFilesRecQueryCondition qc = new SysUlFilesRecQueryCondition();

		qc.setPkId(((BigDecimal) prjContDetail.get("ID")).toString());
		qc.setCfgCd(FncPrjContMainConstant.FNC_PRJ_CONT_CFGCD);
		qc.setCfgDtlCd(FncPrjContMainConstant.FNC_PRJ_CONT_CFGDTLCD_20);
		qc.setTabNm(FncPrjContMainConstant.FNC_PRJ_CONT_DETAIL_TABNM);
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		List<SysUlFilesRecVO> contDetailAttachList = this.sysUlFilesRecService.searchList(qc);
		prjContDetail.put("contDetailAttachList", contDetailAttachList);
	}
	
	//设置风控审核附件
	private void contDetailRiskAttachList(Map<String, Object> prjContDetail) {

		SysUlFilesRecQueryCondition qc = new SysUlFilesRecQueryCondition();

		qc.setPkId(((BigDecimal) prjContDetail.get("ID")).toString());
		qc.setCfgCd(FncPrjContMainConstant.FNC_PRJ_CONT_CFGCD);
		qc.setCfgDtlCd(FncPrjContMainConstant.FNC_PRJ_CONT_CFGDTLCD_30);
		qc.setTabNm(FncPrjContMainConstant.FNC_PRJ_CONT_DETAIL_TABNM);
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		List<SysUlFilesRecVO> contDetailRiskAttachList = this.sysUlFilesRecService.searchList(qc);
		prjContDetail.put("contDetailRiskAttachList", contDetailRiskAttachList);
	}
	
	//设置最终版
	private void setPrjContDetailFinal(Map<String, Object> prjContDetail) {

		BigDecimal prjContDetailFinalBigDecimal = (BigDecimal)prjContDetail.get("CONT_DETAIL_FINAL");
		if(prjContDetailFinalBigDecimal != null) {
			SysUlFilesRecVO prjContDetailFinal = this.sysUlFilesRecService.selectById(prjContDetailFinalBigDecimal.longValue());
			prjContDetail.put("prjContDetailFinal", prjContDetailFinal);
		}
	}
	//设置最终版新
	private void setPrjContDetailFinalN(Map<String, Object> prjContDetail) {
		//旧的最终版 单一版
		SysUlFilesRecVO prjContDetailFinal=new SysUlFilesRecVO();
		BigDecimal prjContDetailFinalBigDecimal = (BigDecimal)prjContDetail.get("CONT_DETAIL_FINAL");
		if(prjContDetailFinalBigDecimal != null) {
			prjContDetailFinal = this.sysUlFilesRecService.selectById(prjContDetailFinalBigDecimal.longValue());
		}
		//新的最终版  列表
		SysUlFilesRecQueryCondition qc = new SysUlFilesRecQueryCondition();
		qc.setPkId(((BigDecimal) prjContDetail.get("ID")).toString());
		qc.setCfgCd(FncPrjContMainConstant.FNC_PRJ_CONT_CFGCD);
		qc.setCfgDtlCd(FncPrjContMainConstant.FNC_PRJ_CONT_CFGDTLCD_60);
		qc.setTabNm(FncPrjContMainConstant.FNC_PRJ_CONT_DETAIL_TABNM);
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		List<SysUlFilesRecVO> prjContDetailFinalList = this.sysUlFilesRecService.searchList(qc);
		if(null!=prjContDetailFinal.getId()){
			prjContDetailFinalList.add(prjContDetailFinal);
		}
		prjContDetail.put("prjContDetailFinalList", prjContDetailFinalList);
	}
	/**
	 * 合同明细详情
	 */
	@RequestMapping("/contDetailView.do")
	public String contDetailView(HttpServletRequest request) {
		String contDetailId = request.getParameter("contDetailId");//合同明细id
		Map<String, Object> prjContDetail = fncPrjContMainService.selectPrjContDetail(Long.valueOf(contDetailId));
		
		request.setAttribute("prjContDetail", prjContDetail);
		request.setAttribute("operate", request.getParameter("operate"));
		request.setAttribute("sysDate", DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DD));
		request.setAttribute("loginUsrNm", CurrentThreadContext.getCurrentUserName());
		request.setAttribute("from", request.getParameter("from"));
		request.setAttribute("applyId", request.getParameter("applyId"));
		
		BaseLogUtils.info(logger, "contDetailView", "合同明细详情 contDetailId:" + contDetailId, CurrentThreadContext.getCurrentUserName());
		return "rfbuss/fncPrjContMain/fncPrjContDetailView";
	}
	
	
	/**
	 * 更新合同明细状态
	 */
	@RequestMapping(value = "/updateContDetailStatus.do")
	@ResponseBody
	public Object updateContDetailStatus(HttpServletRequest request){
		
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		String contDetailId = request.getParameter("contDetailId");
		try {
		
			String contDetailStatus = request.getParameter("contDetailStatus");
			if(StringUtils.isNotBlank(contDetailId) && StringUtils.isNotBlank(contDetailStatus) ) {
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("contDetailId", contDetailId);
				param.put("contDetailStatus", contDetailStatus);
				fncPrjContMainService.updateContDetailStatus(param);
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "save", "操作数据失败" +  ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "save", "操作数据失败" +  ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		BaseLogUtils.info(logger, "updateContDetailStatus", "更新合同明细状态 contDetailId:" + contDetailId, CurrentThreadContext.getCurrentUserName());

		return result;
	}
	
	
	
	/**
	 * 合同明细审核保存
	 */
	@RequestMapping(value = "/auditSave.do")
	@ResponseBody
	public Object auditSave(HttpServletRequest request){
		
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		String contDetailId = request.getParameter("contDetailId");
		try {
			
			String contDetailStatus = request.getParameter("contDetailStatus");
			String contDetailFinal = request.getParameter("contDetailFinal");
			String contDetailOpinion = request.getParameter("contDetailOpinion");
			
			if(StringUtils.isNotBlank(contDetailId) ) {
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("contDetailId", contDetailId);
				param.put("contDetailStatus", contDetailStatus);
				param.put("contDetailFinal", contDetailFinal);
				param.put("contDetailOpinion", contDetailOpinion);
				param.put("crtUsrId", CurrentThreadContext.getCurrentUserId());
				
				fncPrjContMainService.auditSave(param);
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "save", "操作数据失败" +  ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "save", "操作数据失败" +  ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		BaseLogUtils.info(logger, "contDetailId", "合同明细审核保存 contDetailId:" + contDetailId, CurrentThreadContext.getCurrentUserName());
		return result;
	}
	
	/**
	 * 合同明细列表数据
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/selectPrjContOptionList.do")
	@ResponseBody
	public Object selectPrjContOptionList(HttpServletRequest request) {
		String contDetailId = request.getParameter("contDetailId");
		if(StringUtils.isNotBlank(contDetailId)) {
			List<Map<String, Object>> prjContOptionList = fncPrjContMainService.selectPrjContOptionList(Long.valueOf(contDetailId));
			ListPageVO listPageVO = new ListPageVO(prjContOptionList, prjContOptionList.size());
			return listPageVO;
		}
		return null;
	}
	
	
	/**
	 * 保存附件信息
	 */
	@RequestMapping(value = "/uploadAttchment.do", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public Object uploadAttchment(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String attchmnt = request.getParameter("docArray");
		String id = request.getParameter("pkId");
		String flag = request.getParameter("flag");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_UPLOAD_SUCC);
		if(StringUtils.isNotEmpty(attchmnt) && StringUtils.isNotEmpty(id)){
			//上传解析
			try{
				String fileRem = ""; //文件说明
				String cfgDtlCd = ""; //配置子编号
				String tabNm = ""; //数据表名
				String cfgCd = FncPrjContMainConstant.FNC_PRJ_CONT_CFGCD; //配置编号：REF001
				String cfgOrgCd = FncPrjContMainConstant.FNC_PRJ_CONT_CFGORG; //组织架构代码：0000
				//判断标识确定文件配置编码
				if (StringUtils.isNotEmpty(flag)) {
					if("htfj".equals(flag)){//合同明细附件
						fileRem = "合同明细附件";
						tabNm = FncPrjContMainConstant.FNC_PRJ_CONT_DETAIL_TABNM; //合同管理明细表
						cfgDtlCd = FncPrjContMainConstant.FNC_PRJ_CONT_CFGDTLCD_20;
					}else if("htfk".equals(flag)){
						fileRem = "再融资合同明细风控审核附件";
						tabNm = FncPrjContMainConstant.FNC_PRJ_CONT_DETAIL_TABNM; //合同管理明细表
						cfgDtlCd = FncPrjContMainConstant.FNC_PRJ_CONT_CFGDTLCD_30;
					}else if("zhb".equals(flag)){
						fileRem = "再融资合同明细最终版附件";
						tabNm = FncPrjContMainConstant.FNC_PRJ_CONT_DETAIL_TABNM; //合同管理明细表
						cfgDtlCd = FncPrjContMainConstant.FNC_PRJ_CONT_CFGDTLCD_60;
					}else if("openAccount".equals(flag)){
						fileRem = "集团账户开户申请附件";
						tabNm = "FNC_GROUP_COMPANY_ACCOUNT"; 
						cfgDtlCd = "21";
					}else if("closeAccount".equals(flag)){
						fileRem = "集团账户销户申请附件";
						tabNm = "FNC_GROUP_COMPANY_ACCOUNT"; 
						cfgDtlCd = "22";
					}else if("accountData".equals(flag)){
						fileRem = "集团账户开户资料";
						tabNm = "FNC_GROUP_COMPANY_ACCOUNT"; 
						cfgDtlCd = "23";
					}else if("fncCapPayeeInfoBig".equals(flag)){
						fileRem = "付款单附件";//大额付款管理
						tabNm = "FNC_CAP_PAYEE_INFO_BIG"; 
						cfgDtlCd = "24";
					}else{
						result.setSuccess(BaseConstant.IS_YESNO_NO);
						result.setInfo("文件上传标识不能识别！不能上传附件!");
						BaseLogUtils.info(logger, "uploadAttchment", "文件上传标识不能识别.不能上传附件.[flag="+flag+"]", CurrentThreadContext.getCurrentUserName());
						return result;
					}
				}else{
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("文件上传标识为空！不能上传附件!");
					BaseLogUtils.info(logger, "uploadAttchment", "文件上传标识为空.不能上传附件.[flag="+flag+"]", CurrentThreadContext.getCurrentUserName());
					return result;
				}
				Boolean attchmntPass = this.sysUlFilesRecService.addAttchmnt(String.valueOf(id), attchmnt, cfgCd, cfgDtlCd, tabNm, fileRem, null, null, false, cfgOrgCd);
				if(null == attchmntPass || attchmntPass == false){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("附件上传失败!");
					BaseLogUtils.info(logger, "uploadAttchment", "附件上传失败1.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
				}
				result.setData(id);//设置附件关联主键
			}catch (BaseException ex) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(ex.getMessage());
				BaseLogUtils.error(logger, "uploadAttchment", "附件上传失败2.[id="+id+"]", CurrentThreadContext.getCurrentUserName(), ex);
			}catch (Exception ex) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.error(logger, "uploadAttchment", "附件上传失败3.[id="+id+"]", CurrentThreadContext.getCurrentUserName(), ex);
			}
		}
		return result;
	}
	/**
	 * 合同明细列表数据
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/contDetailApplyList.do")
	@ResponseBody
	public Object contDetailApplyList(HttpServletRequest request) {
		String applyId = request.getParameter("applyId");
		if(StringUtils.isNotBlank(applyId)) {
			List<Map<String, Object>> prjContDetailList = fncPrjContMainApplyService.selectPrjContDetailList(Long.valueOf(applyId));
			for (Map<String, Object> prjContDetail : prjContDetailList) {
				prjContDetail.put("ID", prjContDetail.get("FNC_PRJ_CONT_DETAIL_ID"));
				if(prjContDetail.get("FNC_PRJ_CONT_DETAIL_ID")!=null){
					//根据合同明细Id获取合同明细详细信息
					FncPrjContDetailVO detailVo=fncPrjContDetailService.selectById(Long.parseLong(prjContDetail.get("FNC_PRJ_CONT_DETAIL_ID").toString()));
					if(detailVo!=null){
						this.setPrjContDetailAttche(prjContDetail);//设置合同附件
						this.contDetailRiskAttachList(prjContDetail);//设置风控审核附件
						if(detailVo.getContDetailFinal()!=null){
							prjContDetail.put("CONT_DETAIL_FINAL", BigDecimal.valueOf(detailVo.getContDetailFinal()));
						}
						//this.setPrjContDetailFinal(prjContDetail);//设置最终版
						this.setPrjContDetailFinalN(prjContDetail);//设置最终版
						prjContDetail.put("prjContOptionList", fncPrjContMainService.selectPrjContOptionList(((BigDecimal) prjContDetail.get("ID")).longValue()));//风控意见
						if(detailVo.getContDetailArcNum()!=null){
							prjContDetail.put("CONT_DETAIL_ARC_NUM",detailVo.getContDetailArcNum() );//申请归档份数
						}
						if(detailVo.getContDetailArcRealnum()!=null){
							prjContDetail.put("CONT_DETAIL_ARC_REALNUM",detailVo.getContDetailArcRealnum() );//实际归档份数
						}
						prjContDetail.put("contDetailNm", detailVo.getContDetailNm());//合同名称
						prjContDetail.put("contDetailStatus", detailVo.getContDetailStatus());//合同审核状态
						prjContDetail.put("paperContract", detailVo.getPaperContract());//纸质合同归档
						// 合同状态
						Integer contDetailStatus = detailVo.getContDetailStatus();
						if(contDetailStatus != null) {
							SysDictionaryDTO dictionary = sysDictionaryApiService.getCode(FncPrjContMainConstant.SYS_CODE, 
									FncPrjContMainConstant.ORG_CODE, FncPrjContMainConstant.CONT_DETAIL_STS_CD, contDetailStatus.toString());
							if(dictionary != null){
								prjContDetail.put("CONT_DETAIL_STATUS_DES",dictionary.getCodeNm());//合同审核状态文字
							}
						}
						//主合同编号REQ-13349
						prjContDetail.put("mainContractNo", detailVo.getMainContractNo());//合同名称
					}else{
						prjContDetailList.remove(detailVo);
					}
				}
			}
			ListPageVO listPageVO = new ListPageVO(prjContDetailList, prjContDetailList.size());
			return listPageVO;
		}
		BaseLogUtils.info(logger, "contDetailApplyList", "合同明细列表数据applyId :" + applyId, CurrentThreadContext.getCurrentUserName());
		return null;
	}
	
	/**
	 * 批量打包下载
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/batchDownload.do")
    public ModelAndView batchDownload(HttpServletRequest request, HttpServletResponse response) {
		
		String pNo = null;//流程号
		String applyId = request.getParameter("applyId");//流程业务主键id（合同申请id）
		String contDetailNm = request.getParameter("contDetailNm");//合同名称
		String from = request.getParameter("from");//from=riskControlManager 风控总经理节点; from=riskControl 风控经办节点
		String ids = request.getParameter("ids");//附件id
		
		if(StringUtils.isNotBlank(applyId)) {
			Pager page = new Pager();
	        FriBaseInfoQueryCondition condition = new FriBaseInfoQueryCondition();
	        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
	        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
	        condition.setId(Long.valueOf(applyId));
	        page.setCondition(condition);

	        Pager pager = this.fncPrjContMainService.searchFlowPageById(page);
	        List<FriBaseFlowDTO> plist = (List<FriBaseFlowDTO>) pager.getResultList();
	        if(plist != null && plist.size()>0) {
	        	FriBaseFlowDTO friBaseFlowDTO = plist.get(0);
	        	pNo = friBaseFlowDTO.getpNo();
	        }
		}
		
		
		String tmpZipFileName = "";//压缩包名称
		if(StringUtils.isNotBlank(pNo)) {
			tmpZipFileName += pNo;
		}
		if(StringUtils.isNotBlank(contDetailNm)) {
			tmpZipFileName += contDetailNm;
		}
		tmpZipFileName += ".zip";
		
        
        try {
            byte[] buffer = new byte[1024];
            ZipOutputStream out = new ZipOutputStream(response.getOutputStream());

            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-Disposition", "attachment; filename=" + new String( tmpZipFileName.getBytes("UTF-8"), "ISO8859-1" )  );
            request.setCharacterEncoding("UTF-8");

            if (StringUtils.isEmpty(ids)) {
            	ids = "[]";
            }
            JSONArray jsonArray = JSONArray.parseArray(ids);
            SysUlFilesRecQueryCondition condition = new SysUlFilesRecQueryCondition();
            List<String> idList = JSONObject.parseArray(ids, String.class);
            condition.setIdList(idList);
            condition.setSysCd(CurrentThreadContext.getFlServiceSysCd());
            List<SysUlFilesRecDTO> sysUlFilesRecDTOS = this.uploadApiService.searchSysUlFilesRecList(condition);
            Map<String, SysUlFilesRecDTO> SysUlFilesRecMap = new HashMap<String, SysUlFilesRecDTO>();
            for (SysUlFilesRecDTO sysUlFilesRecDTO: sysUlFilesRecDTOS) {
                SysUlFilesRecMap.put(sysUlFilesRecDTO.getId() + "", sysUlFilesRecDTO);
            }
            List<String> list = new ArrayList<String>();
            Map<String, Integer> map = new HashMap<String, Integer>();
            for (int i = 0; i < jsonArray.size(); i++) {
                String id = jsonArray.getString(i);
                SysUlFilesRecDTO sysUlFilesRecDTO = SysUlFilesRecMap.get(id);
                String fileName = sysUlFilesRecDTO.getFileNm() != null ? sysUlFilesRecDTO.getFileNm() : sysUlFilesRecDTO.getDatNm();
//                String filePath = sysUlFilesRecDTO.getFilePath();
//                fileName = fileName + filePath.substring(filePath.lastIndexOf("."));
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(sysUlFilesRecDTO.getAbsLocPath());
                    
                    if("riskControlManager".equals(from)) {//风控总经理节点,下载的文件放不到不同目录
                    	if("20".contentEquals(sysUlFilesRecDTO.getCfgDtlCd())) {
                    		fileName = "合同附件" +File.separator+ fileName;
                    	}else {
                    		fileName = "风控审核" +File.separator+ fileName;
                    	}
                    }
                    
                    if (list.contains(fileName)) {
                        map.put(fileName, map.get(fileName) + 1);
                        fileName = fileName.replace(".", "(" + map.get(fileName) + ").");
                    } else {
                        map.put(fileName, 0);
                    }
                    
                    out.putNextEntry(new ZipEntry(fileName));
                    //下载的文件名写入list
                    list.add(fileName);
                    int bytesRead;
                    while (-1 != (bytesRead = fis.read(buffer, 0, buffer.length))) {
                        out.write(buffer, 0, bytesRead);
                    }
                } catch (Exception e) {
                	e.printStackTrace();
                    BaseLogUtils.error(logger, "batchDownload", "下载打包文件循环中失败!" + id, e);
                } finally {
                    if (null != out) {
                        out.flush();
                        out.closeEntry();
                    }
                    if (null != fis) {
                        fis.close();
                        fis = null;
                    }
                }
            }
            if (null != out) {
                out.finish();
                out.close();
                out = null;
            }
        } catch (Exception e) {
        	e.printStackTrace();
            BaseLogUtils.error(logger, "batchDownload", "下载打包文件失败!", e);
        }
        return null;
    }

	
	
}

